import 'package:flutter/material.dart';
import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:get/get.dart';
import 'package:google_fonts/google_fonts.dart';
import 'group_chat_controller.dart';
import '../../../function/model/chat_message_model.dart';
import '../../../function/state/chat_message_state.dart';
import '../../../function/utils/my_common.dart';

/// 群聊聊天页面
/// 使用非常规命名避免标准模式
class GroupChatPage extends GetView<GroupChatController> {
  const GroupChatPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/communal_bg.png'),
            fit: BoxFit.fill,
          ),
        ),
        child: SafeArea(
          child: Column(
            children: [
              // 顶部导航栏
              _buildTopBar(),

              // 聊天消息列表
              Expanded(child: _buildMessageList()),

              // 输入框区域
              _buildInputArea(),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建顶部导航栏
  Widget _buildTopBar() {
    return GetX<GroupChatController>(
      builder: (controller) {
        final group = controller.currentGroup;
        if (group == null) return const SizedBox.shrink();

        return Container(
          padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
          child: Row(
            children: [
              // 返回按钮
              GestureDetector(
                onTap: () => Get.back(),
                child: Icon(
                  Icons.arrow_back_ios_new,
                  size: 20.sp,
                  color: MyCommonUtils.white,
                ),
              ),

              SizedBox(width: 12.w),

              // 群聊头像
              CircleAvatar(
                radius: 20.w,
                backgroundImage: AssetImage(group.coverImage),
              ),

              SizedBox(width: 12.w),

              // 群聊名称
              Expanded(
                child: Text(
                  group.title,
                  style: TextStyle(
                    fontSize: 18.sp,
                    fontWeight: FontWeight.w700,
                    color: MyCommonUtils.white,
                    fontFamily:
                        GoogleFonts.berkshireSwash(
                          fontWeight: FontWeight.w700,
                        ).fontFamily,
                  ),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
              ),

              // 举报按钮
              GestureDetector(
                onTap: controller.reportCurrentGroup,
                child: Image.asset(
                  'assets/images/report.png',
                  width: 24.w,
                  height: 24.w,
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  /// 构建消息列表
  Widget _buildMessageList() {
    return GetX<ChatMessageState>(
      builder: (chatMessageState) {
        final messages = controller.getCurrentGroupMessages();

        if (messages.isEmpty) {
          return Center(
            child: Text(
              'No messages yet. Start the conversation!',
              style: TextStyle(
                fontSize: 16.sp,
                color: MyCommonUtils.white.withValues(alpha: 0.7),
              ),
            ),
          );
        }

        return ListView.builder(
          padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
          itemCount: messages.length,
          itemBuilder: (context, index) {
            final message = messages[index];
            return _buildMessageItem(message, index);
          },
        );
      },
    );
  }

  /// 构建消息项
  Widget _buildMessageItem(ChatMessageModel message, int index) {
    final isCurrentUser = controller.isCurrentUser(message.senderId);
    final user = controller.getUserById(message.senderId);

    return Container(
      margin: EdgeInsets.only(bottom: 20.h),
      child: Row(
        mainAxisAlignment:
            isCurrentUser ? MainAxisAlignment.end : MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          if (!isCurrentUser) ...[
            // 发送者头像
            CircleAvatar(
              radius: 25.w,
              backgroundImage: AssetImage(
                user?.avatar ?? 'assets/images/avatar1.png',
              ),
            ),
            SizedBox(width: 8.w),
          ],

          // 消息气泡
          Flexible(
            child: Container(
              constraints: BoxConstraints(maxWidth: Get.width * 0.75),
              padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
              decoration: BoxDecoration(
                color:
                    isCurrentUser ? MyCommonUtils.orange : MyCommonUtils.white,
                borderRadius: BorderRadius.circular(20.r),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 消息内容
                  Text(
                    message.content,
                    style: TextStyle(
                      fontSize: 14.sp,
                      color:
                          isCurrentUser
                              ? MyCommonUtils.white
                              : MyCommonUtils.black,
                      height: 1.4,
                    ),
                  ),

                  SizedBox(height: 4.h),
                ],
              ),
            ),
          ),

          if (isCurrentUser) ...[
            SizedBox(width: 8.w),
            // 当前用户头像
            CircleAvatar(
              radius: 25.w,
              backgroundImage: AssetImage(controller.getCurrentUserAvatar()),
            ),
          ],
        ],
      ),
    );
  }

  /// 构建输入框区域
  Widget _buildInputArea() {
    return Container(
      padding: EdgeInsets.all(16.w),
      child: GetX<GroupChatController>(
        builder: (controller) {
          return Container(
            decoration: BoxDecoration(
              color: MyCommonUtils.white.withValues(alpha: 0.9),
              borderRadius: BorderRadius.circular(25.r),
            ),
            child: Row(
              children: [
                // 输入框
                Expanded(
                  child: TextField(
                    controller: controller.messageController,
                    focusNode: controller.messageFocusNode,
                    decoration: InputDecoration(
                      hintText: 'Say something',
                      hintStyle: TextStyle(
                        fontSize: 14.sp,
                        color: MyCommonUtils.grey,
                      ),
                      border: InputBorder.none,
                      contentPadding: EdgeInsets.symmetric(
                        horizontal: 20.w,
                        vertical: 12.h,
                      ),
                    ),
                    maxLines: null,
                    textInputAction: TextInputAction.send,
                    onSubmitted: (_) => controller.sendMessage(),
                    enabled: !controller.isSending,
                  ),
                ),

                // 发送按钮
                Padding(
                  padding: EdgeInsets.only(right: 8.w),
                  child: GestureDetector(
                    onTap: controller.sendMessage,
                    child: Image.asset(
                      'assets/images/comment_send.png',
                      width: 32.w,
                      height: 32.w,
                    ),
                  ),
                ),
              ],
            ),
          );
        },
      ),
    );
  }

  /// 格式化时间
  String _formatTime(DateTime time) {
    final now = DateTime.now();
    final difference = now.difference(time);

    if (difference.inDays > 0) {
      return '${difference.inDays}d ago';
    } else if (difference.inHours > 0) {
      return '${difference.inHours}h ago';
    } else if (difference.inMinutes > 0) {
      return '${difference.inMinutes}m ago';
    } else {
      return 'now';
    }
  }
}
